import { effect, track, trigger, ITERATE_KEY } from "./index.js";

// 5.5 浅响应与深响应

// 封装一个createReactive函数，接受isShallow是否为浅响应 默认false 非浅响应
function createReactive(target, isShallow = false) {
  return new Proxy(target, {
    get(target, key, receiver) {
      if (key === "raw") {
        return target;
      }
      track(target, key);
      const res = Reflect.get(target, key, receiver);
      if (isShallow) return res;
      if (typeof res === "object" && res !== null) {
        return reactive(res);
      }
      return res;
    },
    set(target, key, val, receiver) {
      const oldVal = target[key];
      const type = Object.prototype.hasOwnProperty.call(target, key)
        ? "SET"
        : "ADD";
      const res = Reflect.set(target, key, val, receiver);

      if (target === receiver.raw) {
        // console.log(" receiver 就是 target 的代理对象");
        if (oldVal !== val && (oldVal === oldVal || val === val)) {
          trigger(target, key, type);
        }
      }

      return res;
    },
    has(target, key) {
      return Reflect.has(target, key);
    },
    ownKeys(target, key) {
      track(target, ITERATE_KEY);
      return Reflect.ownKeys(target);
    },
  });
}

function reactive(target) {
  return createReactive(target);
}
function shallowReactive(target) {
  return createReactive(target, true);
}
// 深响应---reactive
// const obj = reactive({
//   a: 1,
//   foo: {
//     bar: 1,
//   },
// });
// effect(() => {
//   console.log(obj.foo.bar);
// });
// obj.foo.bar = 2;
// obj.a = 2;

// 浅响应---shallowReactive
const obj2 = shallowReactive({
  a: 1,
  foo: {
    bar: 1,
  },
});
effect(() => {
  console.log(obj2.foo.bar);
});
// 不是响应的 不能触发副作用函数重新执行
obj2.foo.bar = 2;
// 响应的，可以触发副作用函数重新执行
obj2.foo = { bar: 2 };
